package com.hns.frame.mybatis;

/**
 * oracle方言
 * @author:Fisher
 * @email:zhuangcaijin@126.com
 * @version Revision 2.0.0
 */
public class OracleDialect implements Dialect {

    /**
     * oracle翻页
     * @param sql
     * @param hasOffset
     * @param start
     * @param size
     * @return  返回经过加工的sql
     * @see com.hns.frame.mybatis.Dialect#getLimitString(java.lang.String, boolean, int, int)
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
	public String getLimitString(String sql,boolean hasOffset, int start, int size) {
		int limit = hasOffset ? start + size : size;
		sql = sql.trim();
		boolean isForUpdate = false;
		if (sql.toLowerCase().endsWith(" for update")) {
			sql = sql.substring(0, sql.length() - 11);
			isForUpdate = true;
		}
		StringBuffer pagingSelect = new StringBuffer(sql.length() + 100);
		if (hasOffset) {
			pagingSelect.append("select * from( select * from ( select row_.*, rownum rownum_ from ( ");
		} else {
			pagingSelect.append("select * from ( ");
		}
		pagingSelect.append(sql);
		if (hasOffset) {
			pagingSelect.append(" ) row_ where rownum<=");
			pagingSelect.append(limit);
			pagingSelect.append(" )where rownum_ > ");
			pagingSelect.append(start);
			pagingSelect.append(")");
		} else {
			pagingSelect.append(" ) where rownum <= ").append(limit);
		}
		if (isForUpdate) {
			pagingSelect.append(" for update");
		}
		return pagingSelect.toString();
	}

	public boolean supportsLimit() {
		return true;
	}

	public boolean supportsLimitOffset() {
		return true;
	}
}